/**
 * 用户详情页面交互逻辑
 * 负责加载用户详情数据和处理删除操作
 */
import { fetchDataById, deleteDataItem } from '../../js/api.js';

/**
 * 从URL获取用户ID
 */
function getUserIdFromUrl() {
    const params = new URLSearchParams(window.location.search);
    const id = params.get('id');
    return id ? parseInt(id) : null;
}

/**
 * 渲染用户详情数据
 * @param {Object} data - 用户详情数据
 */
function renderUserDetail(data) {
    document.getElementById('userId').textContent = data.id;
    document.getElementById('username').textContent = data.username;
    document.getElementById('email').textContent = data.email;
    document.getElementById('phone').textContent = data.phone || '-';
    document.getElementById('createdAt').textContent = new Date(data.created_at).toLocaleString();
    document.getElementById('updatedAt').textContent = new Date(data.updated_at).toLocaleString();

    // 设置角色显示
    const roleElement = document.getElementById('role');
    const roleClass = data.role === 'admin' ? 'role-admin' : data.role === 'seller' ? 'role-seller' : 'role-user';
    roleElement.innerHTML = `<span class="status-badge ${roleClass}">${data.role}</span>`;
}

/**
 * 加载用户详情数据
 */
async function loadUserDetail() {
    const id = getUserIdFromUrl();
    if (!id) {
        alert('无效的用户ID');
        window.location.href = 'list.html';
        return;
    }

    try {
        const data = await fetchDataById(id);
        renderUserDetail(data);
    } catch (error) {
        console.error('加载用户详情失败:', error);
        alert('加载用户详情失败: ' + (error.message || '未知错误'));
    }
}

/**
 * 初始化删除按钮事件
 */
function initDeleteButton() {
    const deleteBtn = document.getElementById('deleteBtn');
    deleteBtn.addEventListener('click', async () => {
        const id = getUserIdFromUrl();
        if (!id) return;

        if (confirm('确定要删除此用户吗？此操作不可撤销！')) {
            try {
                const success = await deleteDataItem(id);
                if (success) {
                    alert('用户删除成功！');
                    window.location.href = 'list.html';
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('删除用户失败: ' + (error.message || '未知错误'));
            }
        }
    });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    loadUserDetail();
    initDeleteButton();
});